package com.admin.service.serviceimpl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.admin.mapper.RoleMapper;
import com.admin.service.RoleMenuService;
import com.admin.service.RoleService;
import com.admin.service.RoleUserService;
import com.admin.util.cacheUtil.JedisUtil;
import com.fegin.bean.admin.AdminRole;
import com.fegin.bean.admin.RoleMenu;
import com.fegin.bean.common.layuiBean.ResultPage;
import com.fegin.bean.common.layuiBean.VoPage;
import com.util.Respons.ResponseUtil;
import com.util.exception.CommonException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author 张子艺
 * @since 2019-01-08
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, AdminRole> implements RoleService {
    @Autowired
    JedisUtil jedisUtil;

    @Autowired
    RoleMenuService roleMenuService;

    @Autowired
    RoleUserService roleUserService;

    @Override
    public ResultPage<AdminRole> findRoleByPage(VoPage voPage, int flag, Long loginId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        paramMap.put("flag", flag);
        paramMap.put("loginId", loginId);
        List<AdminRole> list = baseMapper.selectMyPage(paramMap);
        Integer count = baseMapper.countMyPage(paramMap);
        ResultPage<AdminRole> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

    @Override
    public Map<String, Object> findRoleAll(Long loginId, int flag) {
        if(flag==1){
            Map map = new HashMap<>();
            map.put("admin_user_id", loginId);
            List<AdminRole> roles = baseMapper.selectByMap(map);
            return ResponseUtil.getSuccessMap((roles), "操作成功");
        }else{
            Map map = new HashMap<>();
            map.put("admin_user_id", 0);
            List<AdminRole> roles = baseMapper.selectByMap(map);
            return ResponseUtil.getSuccessMap((roles), "操作成功");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> insertRole(String roleName, String menuId, Long userId) {
        List<AdminRole> roles = baseMapper.selectAllRole();
        roles.stream().forEach(s -> {
            if (s.getRoleName().equals(roleName)) {
                throw new CommonException("该角色已存在");
            }
        });
        AdminRole role = new AdminRole();
        role.setAdminUserId(userId);
        role.setRoleName(roleName);
        role.setCreateTime(System.currentTimeMillis());
        role.setRoleValue(UUID.randomUUID() + "");
        if (this.save(role)) {
            String mIds[] = menuId.split(",");
            for (int i = 0; i < mIds.length; i++) {
                Long mid = Long.valueOf(mIds[i]);
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setmId(mid);
                roleMenu.setrId(role.getId());
                if (!roleMenuService.save(roleMenu)) {
                    throw new CommonException("保存角色失败");
                }
            }
        }
        return ResponseUtil.getSuccessMap();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> insertDistribution(String roleName, String menuId, Long userId) {
        AdminRole adminRole = new AdminRole();
        adminRole.setIsLast(0);
        //修改所有的分销商为 不是最后一级
        if (baseMapper.updateDistributionNoLast() > 0) {
            AdminRole role = new AdminRole();
            role.setRoleName(roleName);
            role.setCreateTime(System.currentTimeMillis());
            role.setRoleValue(UUID.randomUUID() + "");
            // role.setAdminUserId(userId);
            role.setAdminUserId(userId);
            if (this.save(role)) {
                String mIds[] = menuId.split(",");
                for (int i = 0; i < mIds.length; i++) {
                    Long mid = Long.valueOf(mIds[i]);
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setmId(mid);
                    roleMenu.setrId(role.getId());
                    if (!roleMenuService.save(roleMenu)) {
                        throw new CommonException("保存分销商失败");
                    }
                }
            }
            return ResponseUtil.getSuccessMap();
            //修改行数为0的时候
        } else {
            throw new CommonException("保存分销商失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> delRole(Long roleId) {
        Map map = new HashMap();
        map.put("role_id", roleId);
        if (roleUserService.listByMap(map).size() > 0) {
            throw new CommonException("不可删除该角色，该角色下还有其他用户的存在");
        }
        map.clear();
        map.put("r_id", roleId);
        if (roleMenuService.removeByMap(map)) {
            if (this.removeById(roleId)) {
                return ResponseUtil.getSuccessMap();
            }
        }
        throw new CommonException("删除失败");
    }
}
